// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const _ = db.command
const canJu = db.collection("canju")
const account = db.collection("account")

// 云函数入口函数
// 登录函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    // 判断playTime是否一致，否则不更新
    let checkCanJuInfo = await canJu.doc(event.canJuId)
      .field({
        canPlay: true,
        playTime: true
      })
      .get()
      let oldTime = new Date(checkCanJuInfo.data.playTime).getTime()
      let playerTime = new Date(event.playTime).getTime()
      if (playerTime != oldTime) {
        return {
          code: 'fail',
          res: null
        }
      }

      if (checkCanJuInfo.data.canPlay) {
        return {
          code: 'fail',
          res: null
        }
      }

    let win
    if ((event.progressTipsNum[0]/event.progressTipsNum[1]) == 1) {
      win = true
    } else {
      win = false
    }
    let res = await canJu.doc(event.canJuId).update({
      data: {
        parentBlockRest: event.parentBlockRest,
        parentBlockDiRest: event.parentBlockDiRest,
        progressTipsNum: event.progressTipsNum,
        totalScoreRest: event.totalScoreRest,
        level: event.level,
        playInfo: _.push({
          openid: wxContext.OPENID,
          score: event.myCanJuScore,
          name: event.name
        }),
        canPlay: true,
        alreadyWheel: event.alreadyWheel,
        win: win
      }
    })
    let canJuPlayInfo
    let allPeopleOpenid
    // 通关的话，给所有上山者通关次数+1
    if (win) {
      canJuPlayInfo = await canJu.doc(event.canJuId)
        .field({
          playInfo: true,
        })
        .get()
      let arr = canJuPlayInfo.data.playInfo
      // 唯一字段值
      allPeopleOpenid = [...new Set(arr.map(obj => obj['openid']))]
      for (let index = 0; index < allPeopleOpenid.length; index++) {
        const element = allPeopleOpenid[index];
        await account
          .where({
            openid: element
          }).update({
            data: {
              passNumber: _.inc(1),
              dayPassNumber: _.inc(1)
            }
          })
      }
    }

    return {
      code: 'ok',
      res: res
    }
  } catch (e) {
    return {
      code: 'fail',
      res: null
    }
  }


}